<?php
class FileWidget extends CInputWidget
{
    /**
     * relative folder from EntryScript
     *
     * @var string
     */
    public $root = Settings::UPLOAD_FOLDER;
    public $ext = array('gif', 'png', 'jpeg', 'jpg');

    public $showButtonRemove = true;

    public function run()
    {
        if (is_object($this->model)) {
            echo CHtml::activeHiddenField($this->model, $this->attribute);
            $id = CHtml::getActiveId($this->model, $this->attribute);
            $value = $this->model->{$this->attribute};
        } else {
            echo CHtml::hiddenField($this->name, $this->value);
            $id = CHtml::getIdByName($this->name);
            $value = $this->value;
        }
        $htmlOptions = array();
        $htmlOptions['class'] = $id . '_trigger';
        $htmlOptions = CMap::mergeArray($htmlOptions, $this->htmlOptions);
        if (empty($value))
            $text = 'Select File';
        else {
            $ext = strtolower(CFileHelper::getExtension($value));
            $name = basename($value);
            if (in_array($ext, $this->ext))
                $text = CHtml::image('/' . trim($value, '/'), $name, array('width' => 100, 'height' => 100));
            else
                $text = $name;
        }
        echo CHtml::link($text, '#', $htmlOptions);
        if ($this->showButtonRemove && empty($value) === false)
            echo '&nbsp;' . CHtml::link('Remove', '#', array('class' => $id . '_remove'));

        $asset = Yii::app()->core->AssetUrl . '/elfinder-1.1';
        $cs = Yii::app()->clientScript;
        $cs->registerCoreScript('jquery.ui');
        $cs->registerScriptFile($asset . '/js/elfinder.min.js', CClientScript::POS_BEGIN);
        $cs->registerCssFile($asset . '/css/elfinder.css');
        $cs->registerCssFile(Yii::app()->theme->baseUrl . '/styles/widgets/jquery.ui.dialog.css');

        $script = "
var currentPopup=null;
\$.updateValue = function(value){
    value = decodeURIComponent(value);
    var trigger = currentPopup;
    var input = trigger.siblings('input').first();
    var inputId = input.attr('id');
    if (value.length)
        value = value.replace('" . Yii::app()->request->hostInfo . Yii::app()->baseUrl . "', '');
    input.val(value);
    var class_name = trigger.attr('class');
    var remove = \$(currentPopup).siblings('.'+inputId+'_remove').first();
    var arr = value.split('.');
    var ext = arr[arr.length-1];
    if (\$.inArray(ext , ['gif', 'jpg', 'png', 'jpeg', 'ico']) >=0 ) {
        trigger.html('<img src=\"'+value+'\" width=\"100\" height=\"100\" />');
    }
    else {
        var arr = value.split('/');
        trigger.html(arr[arr.length-1]);
    }
    if (remove.length <= 0 && " . (int)$this->showButtonRemove . ")
        trigger.after(' <a href=\"#\" class=\"'+inputId+'_remove\">Remove</a>');
    currentPopup = null;
}
";
        $cs->registerScript(__CLASS__ . '#UpdateHiddenValue', $script, CClientScript::POS_READY);

        $params = array('SID' => 'Core.FileManager.cmdConnect');
        $urlManager = new CUrlManager;
        if (empty($this->root) === false)
            $params['root'] = $this->root;
        elseif (isset($this->htmlOptions['location']))
            $params['root'] = $this->htmlOptions['location'];
        $connectorUrl = $urlManager->createUrl('/Core/service/command', $params);

        $script = '$(".' . $htmlOptions['class'] . '").live("click", function(){
    currentPopup = $(this);
    if($("#finder-' . $id . '").length == 0) {
        $("body").append($("<div/>").attr("id", "finder-' . $id . '"));
        $("#finder-' . $id . '").elfinder({
            zIndex: 9999999, 
            places: "Favorites", 
            url : "' . $connectorUrl . '",
            lang : "en",
            dialog : { width : 900, modal : true, title : "File manager", zIndex: 7777777 },
            editorCallback : function(url) {
                $.updateValue(url);
            },
            closeOnEditorCallback: true
        });
    } else {
        $("#finder-' . $id . '").elfinder("open");
    }
    return false;
});';
        $cs->registerScript(__CLASS__ . '#OpenFileManage' . $id, $script, CClientScript::POS_READY);

        $script = "
$('.{$id}_remove').live('click', function(){
    \$(this).siblings('input').first().val('');
    $(this).siblings('.{$id}_trigger').first().empty().text('Select File');
    $(this).remove();
    return false;
});
";
        $cs->registerScript(__CLASS__ . '#RemoveItem' . $id, $script, CClientScript::POS_READY);
    }
}